/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.cdyj.controller;

import com.dmgis.entity.DmMapRectangle;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.businessservice.yysl.service.IWaternfoService;
import com.dmgis.qxfw.dataservice.businessservice.cdyj.service.IEmergencyService;

import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.weblib.MapCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.Point2D;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * This class is used for 应急
 *
 * @author dsq
 * @version 1.0, 2018年8月21日 上午10:37:45
 */
@Controller
@RequestMapping("/xtyj")
public class EmergencyController {
    private  final String operatingSystem;

    @Autowired
    public EmergencyController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    @Resource
    IEmergencyService emergencyService;

    @Resource
    private IWaternfoService forecastInfoService;


    @Resource
    private IQxInfoService qxInfoService;

    @Resource
    private ITransformService transformService;

    MongoService1 mongoService=new MongoService1();



    /**
     * 根据名称和id查询安监站点
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/getAnjianPoint")
    @ResponseBody
    public Object getAnjianByNameandId(HttpServletRequest request, Model model) {
        String staName = request.getParameter("stationName");
        String staId = request.getParameter("stationId");
        List<special_srv_station> resultList = new ArrayList<special_srv_station>();
        resultList = emergencyService.getAnjianByNameandId(staName, staId);
        if (resultList != null && resultList.size() > 0) {
            for (special_srv_station srv : resultList) {
                srv.setLon(srv.getLongitude());
                srv.setLat(srv.getLatitude());
            }
        }
        return resultList;
    }


    /**
     * 获取安监预报根据半径精度纬度
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/AnjianYuBao")
    @ResponseBody
    public Object getAnjianYuBao(HttpServletRequest request, Model model) {
        String r = request.getParameter("pos");// 半径
        String lon = request.getParameter("lon");// 精度
        String lat = request.getParameter("lat");// 纬度
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        //气象数据操作类
        WebCtrlData wcd = new WebCtrlData();
        try {
            //云平台相关功能
            List<township_forecasttemp> fcstList = emergencyService.getAnjianFcst(r, lon, lat);
            int count = fcstList.toArray().length;
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < count; i += 2) {
                Point2D center = new Point2D.Double(Double.parseDouble(lon), Double.parseDouble(lat));//
                Point2D yidong = new Point2D.Double(fcstList.get(i).getLongitude(), fcstList.get(i).getLatitude());
                Double d = getDistance(center, yidong);
                if (getDistance(center, yidong) < Double.parseDouble(r)) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                if (strCountyName.contains("乡")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                }
                if (strCountyName.contains("镇")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                }
                if (strCountyName.contains("市")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('市') + 1);
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindd().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWinds())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWinds())));
                String windS12 = String.valueOf(fcstList.get(i).getWinds());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWinds());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i).getMaxtemp() > fcstList.get(i + 1).getMaxtemp()
                        ? fcstList.get(i).getMaxtemp() : fcstList.get(i + 1).getMaxtemp();
                double minTemp = fcstList.get(i).getMintemp() > fcstList.get(i + 1).getMintemp()
                        ? fcstList.get(i + 1).getMintemp() : fcstList.get(i).getMintemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                String datechar = format.format(fcstList.get(i).getDatechar());
                Date date = format.parse(datechar);
                DateTime dateTime = new DateTime(date);
                String time1 = dateTime.AddDays(+1).toDateString();
                fcstInfo.setTime1(time1);
                fcstInfo.setTime(datechar);
                fcstInfo.setDatechar(fcstList.get(i).getDatechar());
                fcstInfo.setTimechar(fcstList.get(i).getTimechar());
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                DmMapPoint dt = new DmMapPoint();
                dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
                }
            }
        } catch (Exception e) {
            // TODO: 预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }

    /**
     * 获取安监实况
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/AnjianSKInfo")
    @ResponseBody
    public Object getAnjianSKInfo(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();//开始时间
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();//结束时间
        String element = request.getParameter("element");//类型
        String lon = request.getParameter("lon");//精度
        String lat = request.getParameter("lat");//纬度
        String r = request.getParameter("r");//半径
        //实况要素查询类
        ActualElemQuery elemQuery = new ActualElemQuery();
        //Element 要素
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        List<MsgMediumSmallScale> resultList = emergencyService.getAnjianSKInfo(elemQuery);
        List<ActualData> acresultList = new ArrayList<ActualData>();
        // 赋值
        try {
            if (resultList.size() > 0) {
                for (MsgMediumSmallScale data : resultList) {
                    Point2D center = new Point2D.Double(Double.parseDouble(lon), Double.parseDouble(lat));//
                    Point2D yidong = new Point2D.Double(data.getLongitude(), data.getLatitude());
                    if (getDistance(center, yidong) < Double.parseDouble(r)) {
                        ActualData actualData = new ActualData();
                        actualData.setStationId(data.getStationid().trim());
                        actualData.setStationName(data.getStationname().trim());
                        actualData.setLon(data.getLongitude());
                        actualData.setLat(data.getLatitude());
                        DmMapPoint dt = transformService.LonLatConvertToLambert(data.getLongitude(), data.getLatitude());
                        actualData.setX(dt.x);
                        actualData.setY(dt.y);
                        actualData.setRain(Double.parseDouble(String.format("%.1f", data.getRain())));
                        actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getDrybulbtemp())));
                        actualData.setWinds(Double.parseDouble(String.format("%.1f", data.getInstantwindv())));
                        actualData.setPressure(Double.parseDouble(String.format("%.1f", data.getStationpress())));
                        if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            actualData.setDateTime(sdf.parse(data.getDatechar()));
                        } else {
                            actualData.setDateTime(data.getObservtime());
                        }
                        acresultList.add(actualData);
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return acresultList;
    }
    /**
     * 灾害点分析
     *
     * @return
     * @author liujia
     * @date 2019年9月25日
     */
    @RequestMapping("/DisPointInfo")
    @ResponseBody
    public Object DisPointInfo(HttpServletRequest request, Model model) throws ParseException {
        String lon = request.getParameter("lon");//精度
        String lat = request.getParameter("lat");//纬度
        String r = request.getParameter("r");//半径
        DPoint selectKey = new DPoint();// 查询类
        List<potential_points> resultList = forecastInfoService.getDPoint(selectKey);
        String result = "[";
        try {
            if (resultList.size() > 0) {
                for (potential_points point : resultList) {
                    Point2D center = new Point2D.Double(Double.parseDouble(lon), Double.parseDouble(lat));//
                    Point2D yidong = new Point2D.Double(Double.parseDouble(point.getLon()), Double.parseDouble(point.getLat()));
                    if (getDistance(center, yidong) < Double.parseDouble(r)) {
                        result += "{";
                        result += "\"disastername\":\"" + point.getPp_name().trim() + "\",";
                        result += "\"disasterscale\":\"" + point.getDis_scale().trim() + "\",";
                        result += "\"dis_type\":\"" + point.getDis_type().trim() + "\",";
                        result += "\"disName\":\"" + point.getPp_name().trim() + "\",";
                        result += "\"threatproperty\":\"" + point.getThreat_pop() + "\",";
                        result += "\"threathouseholds\":\"" + point.getThreat_prop() + "\",";
                        result += "\"monitorperson\":\"" + point.getContact().trim() + "\",";
                        result += "\"tel\":\"" + point.getContact_tel().trim() + "\",";
                        result += "\"monitorprincipal\":\"" + point.getContact1().trim() + "\",";
                        result += "\"monitorprincipaltel\":\"" + point.getContact1_tel().trim() + "\",";
                        result += "\"lon\":" + Double.parseDouble(point.getLon()) + ",";
                        result += "\"lat\":" + Double.parseDouble(point.getLat()) + "";
                        result += "},";
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.getStackTrace());
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    /**
     * 村点分析
     *
     * @return
     * @author liujia
     * @date 2019年9月25日
     */
    @RequestMapping("/VallagePointInfo")
    @ResponseBody
    public Object VallgePointInfo(HttpServletRequest request, Model model) throws ParseException {
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String r = request.getParameter("r");
        List<village> resultList = qxInfoService.getCountryPoint(null);
        String result = "[";
        try {
            if (resultList.size() > 0) {
                for (village point : resultList) {
                    Point2D center = new Point2D.Double(Double.parseDouble(lon), Double.parseDouble(lat));//
                    Point2D yidong = new Point2D.Double(point.getLon(), point.getLat());
                    if (getDistance(center, yidong) < Double.parseDouble(r)) {
                        result += "{";
                        result += "\"dmgisId\":\"" + point.getId() + "\",";
                        result += "\"stationName\":\"" + point.getVillagename() + "\",";
                        result += "\"population\":\"" + point.getPopulation() + "\",";
                        result += "\"mayor\":\"" + point.getVillagehead() + "\",";
                        result += "\"tel\":\"" + point.getContacttel() + "\",";
                        result += "\"lon\":" + point.getLon() + ",";
                        result += "\"lat\":" + point.getLat() + ",";
                        result += "\"county\":\"" + point.getCountry() + "\"";
                        result += "},";
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.getStackTrace());
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    /**
     * 获取应急常规服务产品信息
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getYjWord")
    @ResponseBody
    public Object getSYCommonWord(HttpServletRequest request, Model model) throws ParseException {
        List<base_product> resultList = emergencyService.getYjWord();
        return resultList;
    }


    /**
     * 下载应急常规服务产品
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showYjDoc")
    @ResponseBody
    public Object showCommonDoc(HttpServletRequest request, Model model) throws ParseException {
        String servicePath = "";
        String id = request.getParameter("id");// 获取编号
        String fileName = request.getParameter("filename");

        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\YjWord\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/YjWord/";// 临时文件目录
        }


        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        if (doctype.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){

                    servicePath = "Temp\\YjWord\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/YjWord/" + fileName.replace(doctype, "pdf");
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data.length > 0) {
                    FileUtil.bytesToFile(data, pdfPath);
                    // 下载doc文件
                    if (data == null) {
                        return "";
                    }
                    File localFile = new File(pdfPath);// 本地文件
                    if (localFile.exists()) {
                        try {
                            if (operatingSystem.equals("Windows")){
                                servicePath = "Temp\\YjWord\\" + fileName.replace(doctype, "pdf");
                            }else {
                                servicePath = "Temp/YjWord/" + fileName.replace(doctype, "pdf");
                            }

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }


    /**
         * 初始化灾害性天气类型
         *
         * @param
         * @return
     * @author ymf
     * @date 2019/12/23
     **/
    @RequestMapping("/InitdisasterType")
    @ResponseBody
    public Object InitdisasterType() {
        List<disweather_moni_condition> types = emergencyService.InitdisasterType();
        return types;
    }


    /**
     * 查询灾害性天气下载图片
     *
     * @param
     * @return
     * @author
     * @date 2019/12/23
     **/
    @RequestMapping("/GetdisasterInfo")
    @ResponseBody
    public Object GetdisasterInfo(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String type = request.getParameter("type");
        disweather_moni_info disweather = new disweather_moni_info();

        disweather.setStartDate(DateTime.parseDateTime(startDate).toDateTimeString());
        disweather.setEndDate(DateTime.parseDateTime(endDate).toDateTimeString());
        disweather.setDisweather_name(type);
        List<disweather_moni_info> resultList = emergencyService.GetdisasterInfo(disweather);
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\灾害性天气\\";
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/灾害性天气/";
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当图片达到1000张时清除
        FileUtil.ClearTempFiles(urlpath, 1000);

        for (disweather_moni_info doppler : resultList) {

            String fileName = doppler.getDisweather_name() + new DateTime(doppler.getHappen_time()).toDateString() + ".png";
            String servicePath = urlpath + fileName;
            File serviceFile = new File(servicePath);
            if (serviceFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    doppler.setImgPath("Temp\\灾害性天气\\" + fileName);
                }else {
                    doppler.setImgPath("Temp/灾害性天气/" + fileName);
                }

            } else {
                // 从mongdb获取图片
                String types = "";
                if (doppler.getDisweather_name().contains("旱") || doppler.getDisweather_name().contains("干")) {
                    types = "干旱";
                } else {
                    types = doppler.getDisweather_name();
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datechar", new DateTime(doppler.getHappen_time()).toDateString());
                map.put("type", types);
                map.put("collectionName", "disweather_png_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    doppler.setImgPath("images/none.jpg");
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    if (operatingSystem.equals("Windows")){
                        doppler.setImgPath("Temp\\灾害性天气\\" + fileName);
                    }else {
                        doppler.setImgPath("Temp/灾害性天气/" + fileName);
                    }

                }
            }
        }
        // 拼接路径
        return resultList;
    }

    /**
     * 查询灾害性天气地图显示点根据时间和类型
     *
     * @param
     * @return
     * @author ymf
     * @date 2019/12/23
     **/
    @RequestMapping("/ShowDisaster")
    @ResponseBody
    public Object ShowDisaster(HttpServletRequest request) throws Exception {
        String time = request.getParameter("time");
        String type = request.getParameter("type");
        List<disweather_moni_info> resultList = emergencyService.ShowDisaster(time, type);
        return resultList;
    }


    /**
     * 灾害性天气历史对比曲线图
     *
     * @param
     * @return
     * @author ymf
     * @date 2019/12/23
     **/
    @RequestMapping("/DisasterCharts")
    @ResponseBody
    public Object DisasterCharts(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String stationid = request.getParameter("stationid");
        String element = request.getParameter("element");
        String chartType = request.getParameter("chartType");
        List<ActualData> resultList = emergencyService.qxElementQuery(startDate, endDate, stationid, element, chartType);
        // 处理成曲线图
        List<Integer> hours = new ArrayList<Integer>();
        Map<String, List<Double>> stationValMap = new HashMap<String, List<Double>>();
        for (ActualData actualData : resultList) {
            String stationName = actualData.getStationName().trim();
            if (stationName.equals(resultList.get(0).getStationName().trim())) {
                hours.add(new DateTime(actualData.getDateTime()).GetHour());
            }
            double value = 0d;
            switch (element) {
                case "rain":
                    value = actualData.getRain();
                    break;
                case "temp":
                    value = actualData.getTemp();
                    break;
                case "winds":
                    value = actualData.getWinds();
                    break;
                case "humid":
                    value = actualData.getHumid();
                    break;
                case "pressure":
                    value = actualData.getPressure();
                default:
                    break;
            }
            if (!stationValMap.keySet().contains(stationName)) {
                List<Double> values = new ArrayList<Double>();

                values.add(value);
                stationValMap.put(stationName, values);
            } else {
                stationValMap.get(stationName).add(value);
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap.get(key));
            result.add(tempArr);
        }
        return result;
    }


    /**
     * 初始化水情最新时间
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/initWeater")
    @ResponseBody
    public Object initWeater(HttpServletRequest request, Model model) {
        ArrayList<Object> objects = new ArrayList<>();
        Date o = emergencyService.initWeater();
        DateTime date = new DateTime(o);
        objects.add(date.toDateTimeString());
        return objects;
    }

    /**
     * 获取水位监测值
     *
     * @param
     * @return
     * @author ymf
     * @date 2019/12/23
     **/
    @RequestMapping("/Weater")
    @ResponseBody
    public Object getWeaterByDate(HttpServletRequest request, Model model) {
        String date = request.getParameter("Date") + ":00:00";
        List<water> waterslist = new ArrayList<>();
        List<water_station> list = emergencyService.WeaterStation();
        List<String> station = new ArrayList<String>();
        if (list!=null&&list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                station.add(list.get(i).getStnm());
            }
        }
        List<water> water = emergencyService.Water(station, date);
        if (water!=null&&water.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                water waters = new water();
                for (int j = 0; j < water.size(); j++) {
                    if (list.get(i).getStnm().equals(water.get(j).getStationname())) {
                        waters.setLat(Double.parseDouble(list.get(i).getLttd()));
                        waters.setLon(Double.parseDouble(list.get(i).getLgtd()));
                        waters.setStationid(water.get(j).getStationid());
                        waters.setStationname(water.get(j).getStationname());
                        waters.setLatestobservetime(water.get(j).getLatestobservetime());
                        waters.setSmallscalewaterstatus(water.get(j).getSmallscalewaterstatus());
                        waterslist.add(waters);
                    }
                }
                if (i >= water.size()) {
                    waters.setLat(Double.parseDouble(list.get(i).getLttd()));
                    waters.setLon(Double.parseDouble(list.get(i).getLgtd()));
                    waters.setStationid(list.get(i).getStationid());
                    waters.setStationname(list.get(i).getStnm());
                    waters.setSmallscalewaterstatus(-999.0);
                    waterslist.add(waters);
                }

            }
        }
        return waterslist;
    }


    /**
     * 水位监测值曲线图
     *
     * @param
     * @return
     * @author ymf
     * @date 2019/12/23
     **/
    @RequestMapping("/WaterChart")
    @ResponseBody
    public Object getWaterChart(HttpServletRequest request) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String stationname = request.getParameter("stationname");
        List<water> list = emergencyService.WaterChart(startDate, endDate, stationname);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        Map<String, List<Double>> stationValMap = new HashMap<String, List<Double>>();
        for (water actualData : list) {
            String stationName = actualData.getStationname().trim();
            if (stationName.equals(list.get(0).getStationname().trim())) {
                hours.add(new DateTime(actualData.getLatestobservetime()).toDateTimeHm());
            }
            if (!stationValMap.keySet().contains(stationName)) {
                List<Double> values = new ArrayList<Double>();
                values.add(actualData.getSmallscalewaterstatus());
                stationValMap.put(stationName, values);
            } else {
                stationValMap.get(stationName).add(actualData.getSmallscalewaterstatus());
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap.get(key));
            result.add(tempArr);
        }
        return result;
    }


    /**
     * 查询火源点最新时间
     *
     * @param
     * @return
     * @author
     * @date 2019/12/24
     **/
    @RequestMapping("/initFireTime")
    @ResponseBody
    public Object initFireTime() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(emergencyService.initFireTime());
        result.add(endDate.AddMonths(-1).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }

    /**
     * 根据时间查询火源点信息
     *
     * @param
     * @return
     * @author
     * @date 2019/12/24
     **/
    @RequestMapping("/Firepoint")
    @ResponseBody
    public Object getFirepointByDate(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate") + ":00:00";
        String endDate = request.getParameter("endDate") + ":59:59";
        List<satellitenephoram3> sate = emergencyService.getFirepoint(startDate, endDate);
        return sate;
    }


    /**
     * 通过AB点经纬度获取距离
     *
     * @param pointA A点(经，纬)
     * @param pointB B点(经，纬)
     * @return 距离(单位 ： 米)
     */
    Double getDistance(Point2D pointA, Point2D pointB) {
        double EARTH_RADIUS = 6371393; // 平均半径,单位：m
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(pointA.getX()); // A经弧度
        double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度
        double radiansBX = Math.toRadians(pointB.getX()); // B经弧度
        double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
                + Math.sin(radiansAY) * Math.sin(radiansBY);
        double acos = Math.acos(cos); // 反余弦值
        return EARTH_RADIUS * acos; // 最终结果
    }
    /**
     *预警信息页面预警信号功能初始化
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/showWarning")
    @ResponseBody
    public Object showWarning(HttpServletRequest request, Model model) throws Exception {
        String startDate = request.getParameter("startDate") + " 00:00:00";
        String endDate = request.getParameter("endDate") + " 23:59:59";
        List<warning> resultList = emergencyService.getWarningInfo(startDate, endDate, -1);// 查询时间段内的预警信息号
        for (warning warn : resultList) {
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            Double lon = 0.0;
            Double lat = 0.0;
            if (!StringUtil.IsNullOrEmpty(warn.getPos())) {
                String[] posArr = warn.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = warn.getColor();
                        String colors = "";
                        switch (strColor) {
                            case "蓝色":
                                colors = ColorUtil.Color2String(Color.BLUE);
                                break;
                            case "黄色":
                                colors = ColorUtil.Color2String(Color.YELLOW);
                                break;
                            case "橙色":
                                colors = ColorUtil.Color2String(Color.ORANGE);
                                break;
                            case "红色":
                                colors = ColorUtil.Color2String(Color.RED);
                                break;
                        }
                        // 16进制颜色
                        cEntity.setColor(colors);
                        String[] dotset = pos.split(";");
                        int i = 0;
                        DmMapPoint[] points = new DmMapPoint[dotset.length];
                        Integer index = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            points[index] = dmDot;
                            index ++;
                            i++;
                        }
                        DmMapRectangle rct = new DmMapRectangle();
                        MapCommon dmMapCom = new MapCommon();
                        int[] parts = new int[1];
                        parts[0] = points.length;
                        DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
                        DmMapPoint ltDotCenter = transformService.LambertConvertToLonLat(dmdotCenter.x, dmdotCenter.y);
                        lon = ltDotCenter.x;
                        lat = ltDotCenter.y;
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
            }
            warn.setEntites(cEntities);
            warn.setTime(new DateTime(warn.getAnnouncedtime()).toDateTimeString());
        }
        return resultList;// 查询时间段内的预警信息号
    }
}
